<template>
  <div>
    小区详情{{villageInfo}}
    <Card>
      <tables
        style="margin-bottom: 5px"
        ref="tables"
        editable
        searchable
        search-place="top"
        v-model="tableData"
        :columns="columns"
        @on-delete="handleDelete"
        @on-add="handleAdd"
        @on-save-edit="handleEdit"
      >
      </tables>
      <div>
        <Page
          :total="total"
          :current.sync="current"
          show-elevator
          show-total
          @on-change="handlePageChange"
        />
      </div>
      <!--div style="text-align: right">
        <Button style="margin: 10px 0" type="primary" @click="exportExcel">导出为Csv文件</Button>
      </div-->
    </Card>
    <Drawer title="增加楼栋" :closable="false" v-model="drawer" width="400">
      <Form :model="formItem" :label-width="80">
        <FormItem label="名字">
          <Input v-model="formItem.name" placeholder="输入名字，例如5号楼"></Input>
        </FormItem>
        <!--FormItem label="Select">
          <Select v-model="formItem.select">
            <Option value="beijing">New York</Option>
            <Option value="shanghai">London</Option>
            <Option value="shenzhen">Sydney</Option>
          </Select>
        </FormItem>
        <FormItem label="DatePicker">
          <Row>
            <Col span="11">
              <DatePicker
                type="date"
                placeholder="Select date"
                v-model="formItem.date"
              ></DatePicker>
            </Col>
            <Col span="2" style="text-align: center">-</Col>
            <Col span="11">
              <TimePicker
                type="time"
                placeholder="Select time"
                v-model="formItem.time"
              ></TimePicker>
            </Col>
          </Row>
        </FormItem>
        <FormItem label="Radio">
          <RadioGroup v-model="formItem.radio">
            <Radio label="male">Male</Radio>
            <Radio label="female">Female</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="Checkbox">
          <CheckboxGroup v-model="formItem.checkbox">
            <Checkbox label="Eat"></Checkbox>
            <Checkbox label="Sleep"></Checkbox>
            <Checkbox label="Run"></Checkbox>
            <Checkbox label="Movie"></Checkbox>
          </CheckboxGroup>
        </FormItem>
        <FormItem label="Switch">
          <i-switch v-model="formItem.switch" size="large">
            <span slot="open">On</span>
            <span slot="close">Off</span>
          </i-switch>
        </FormItem>
        <FormItem label="Slider">
          <Slider v-model="formItem.slider" range></Slider>
        </FormItem>
        <FormItem label="Text">
          <Input
            v-model="formItem.textarea"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 5 }"
            placeholder="Enter something..."
          ></Input>
        </FormItem-->
        <FormItem>
          <Button type="primary" @click="handleSubmit">提交</Button>
          <!--Button style="margin-left: 8px">取消</Button-->
        </FormItem>
      </Form>
      <p>{{ formItem }}</p>
      <!--p>456</p-->
    </Drawer>
  </div>
</template>

<script>
import Tables from '_c/tables'
import {
  getVillage,
  getBuildingList,
  addBuilding,
  deleteBuilding,
  updateBuilding
} from '@/api/index'

export default {
  name: 'village_page',
  components: {
    Tables
  },
  data () {
    return {
      villageInfo: null,
      formItem: {
        name: '',
        v_id: (() => { return this.$route.params.id })()
      },
      drawer: false,
      columns: [
        { title: 'ID', key: 'id', sortable: true },
        { title: '名字', key: 'name', editable: true },
        // { title: '创建时间', key: 'createdAt' },
        { title: '更新时间', key: 'updatedAt' },
        {
          title: '操作',
          key: 'handle',
          // options: ['delete'],
          button: [
            (h, params, vm) => {
              return h(
                'Poptip',
                {
                  props: {
                    confirm: true,
                    title: '你确定要删除吗?'
                  },
                  on: {
                    'on-ok': () => {
                      vm.$emit('on-delete', params)
                      vm.$emit(
                        'input',
                        params.tableData.filter(
                          (item, index) => index !== params.row.initRowIndex
                        )
                      )
                    }
                  }
                },
                [h('Button', '删除')]
              )
            },
            (h, params, vm) => {
              return h('Button', {
                props: {
                  type: 'text',
                  size: 'small'
                },
                on: {
                  click: () => {
                    this.handleView(params.row.id)
                  }
                }
              }, '查看')
            }

          ]
        }
      ],
      tableData: [],
      total: 0,
      current: 1
    }
  },
  watch: {
    '$route.path': function (newVal, oldVal) {
      this.getVillage()
      this.getBuildingList()
    }
  },
  mounted () {
    this.getVillage()
    this.getBuildingList()
  },
  methods: {
    getVillage () {
      const { id } = this.$route.params
      getVillage(id).then(res => {
        this.villageInfo = res.data
      })
    },
    getBuildingList (pageNum = 1) {
      this.current = pageNum
      const limit = 10
      const offset = (pageNum - 1) * limit
      let { id } = this.$route.params
      let query = { v_id: id, limit, offset }
      getBuildingList(query).then(res => {
        const { count, rows } = res.data
        this.total = count
        this.tableData = rows
      })
    },
    handleView (id) {
      this.$router.push(`/manage/building/${id}`)
    },
    handlePageChange (num) {
      // 1,2
      this.getVillageList(num)
    },
    handleEdit (td) {
      let key = td.column.key
      let newValue = td.value
      let data = Object.assign(td.row, { [key]: newValue })

      updateBuilding(data).then((res) => {
        const { id } = res.data
        if (id) {
          this.$Notice.success({
            title: '更新成功'
          })
          this.getBuildingList(this.current)
        }
      })
    },
    handleAdd () {
      this.drawer = true
    },
    handleSubmit () {
      addBuilding(this.formItem).then((res) => {
        const { id } = res.data
        if (id) {
          this.$Notice.success({
            title: '成功',
            desc: `ID是${id}`
          })
          this.formItem = {
            name: '',
            v_id: (() => { return this.$route.params.id })()
          }
          this.drawer = false
          this.getBuildingList()
        } else {
          this.$Notice.error({
            title: '失败',
            desc: res.msg
          })
        }
      })
    },
    handleDelete (params) {
      const { id } = params.row
      deleteBuilding(id).then((res) => {
        const { changerows } = res.data
        if (changerows) {
          this.$Notice.success({
            title: '成功'
            // desc: `ID是${data}`
          })
          this.getBuildingList()
        }
      })
    },
    exportExcel () {
      this.$refs.tables.exportCsv({
        filename: `table-${new Date().valueOf()}.csv`
      })
    }
  }
}
</script>

<style>
</style>
